Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    article: null,
    relatedArticles: [],
    errorMessage: '',
    liked: false,
    categories: {
      'disease': '疾病预防',
      'diet': '营养饮食',
      'exercise': '运动健身',
      'medication': '用药指南',
      'prevention': '健康预防',
      'other': '其他'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id } = options;
    if (!id) {
      this.setData({
        loading: false,
        errorMessage: '缺少文章ID'
      });
      return;
    }
    
    this.articleId = id;
    this.loadArticle(id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    if (this.articleId) {
      this.loadArticle(this.articleId);
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const { article } = this.data;
    if (article) {
      return {
        title: article.title,
        path: `/pages/knowledge/detail/detail?id=${article.id}`,
        imageUrl: article.coverImage
      };
    }
    return {
      title: '健康知识',
      path: '/pages/knowledge/knowledge'
    };
  },

  /**
   * 加载文章详情
   */
  loadArticle: function(id) {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    wx.request({
      url: `http://localhost:3000/api/knowledge/articles/${id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const article = res.data.data.article;
          
          // 添加分类名称字段
          article.categoryName = this.data.categories[article.category] || '其他';
          
          this.setData({
            article: article,
            loading: false
          });
          
          // 加载相关文章
          this.loadRelatedArticles(article.category, article.id);
          
          // 更新页面标题
          wx.setNavigationBarTitle({
            title: article.title.substring(0, 12) + (article.title.length > 12 ? '...' : '')
          });
        } else {
          console.error('获取文章详情失败:', res.data.message);
          this.setData({ 
            loading: false,
            errorMessage: res.data.message || '获取文章详情失败'
          });
          wx.showToast({
            title: res.data.message || '获取文章详情失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ 
          loading: false,
          errorMessage: '网络错误，请稍后重试'
        });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 加载相关文章
   */
  loadRelatedArticles: function(category, currentId) {
    const token = wx.getStorageSync('token');
    if (!token) return;
    
    wx.request({
      url: `http://localhost:3000/api/knowledge/articles?category=${category}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const articles = res.data.data.articles || [];
          
          // 过滤掉当前文章，最多显示3篇相关文章
          const relatedArticles = articles
            .filter(article => article.id !== parseInt(currentId))
            .slice(0, 3);
          
          this.setData({
            relatedArticles: relatedArticles
          });
        }
      }
    });
  },

  /**
   * 点赞文章
   */
  likeArticle: function() {
    if (this.data.liked) return;
    
    const token = wx.getStorageSync('token');
    if (!token) return;
    
    const id = this.articleId;
    
    wx.request({
      url: `http://localhost:3000/api/knowledge/articles/${id}/like`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          // 更新点赞状态和数量
          this.setData({
            liked: true,
            'article.likeCount': res.data.data.likeCount
          });
          
          wx.showToast({
            title: '点赞成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.message || '点赞失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 查看相关文章
   */
  viewRelatedArticle: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/knowledge/detail/detail?id=${id}`
    });
  },

  /**
   * 返回文章列表
   */
  goBack: function() {
    wx.navigateBack({
      delta: 1
    });
  }
}) 